import React, { Component } from "react";
import { Table } from "antd";
import { connect } from "react-redux";
import { testapi } from "@service/form";


function mapStateToProps(state) {
  return {
    apiProviders: state.apiProvider,
  };
}
@connect(mapStateToProps)
class QueryPicker extends Component {
  state = {
    selectedRowKeys: [], // Check here to configure the default column
    dataSource: [],
    columns: [],
  };

  componentWillReceiveProps=(props) => {
    const { apiProviders, getData } = props;
    const selectedApi = apiProviders.find(api => api.id === getData().datasource.apiId);
    if(selectedApi){
      testapi(selectedApi.url).then(
        ({ data }) => {
          const { keylist } = selectedApi;
          this.setState({
            columns: keylist,
            dataSource: data,
          });
        }
      );
    }
  }

  onSelectChange = selectedRowKeys => {
    this.setState({ selectedRowKeys });
  };

  render() {
    const { selectedRowKeys, dataSource, columns } = this.state;
    const { getStyle } = this.props;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      hideDefaultSelections: true,
      onSelection: this.onSelection,
    };
    return (columns.length ? (
      <Table
        rowSelection={rowSelection}
        dataSource={dataSource} style={getStyle()}
      >
        {columns.map(column => (
          <Table.Column
            title={column.title} dataIndex={column.dataIndex}
            key={column.dataIndex}
          />
        ))}

      </Table>
    ) : null);
  }
}

export default QueryPicker;
